﻿namespace Net7Docker.BackHostService
{
    /// <summary>
    /// 定时执行后台程序
    /// </summary>
    public class TimedHostedService : IHostedService, IDisposable
    {
        //临时参数
        private int executionCount = 0;
        private readonly ILogger<TimedHostedService> _logger;
        private Timer _timer = null;

        /// <summary>
        /// ctor注册logger组件
        /// </summary>
        /// <param name="logger"></param>
        public TimedHostedService(ILogger<TimedHostedService> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 释放对象
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void Dispose()
        {
            _timer?.Dispose();
        }

        /// <summary>
        /// 开启后台服务
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            //打印日志
            _logger.LogInformation("Timed Hosted Service running");

            //具体时间点执行任务(每隔5s执行一下任务)
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

            return Task.CompletedTask;
        }

        /// <summary>
        /// 定时需要执行的任务
        /// </summary>
        /// <param name="state"></param>
        private void DoWork(object? state)
        {
            //线程安全的递增
            var count = Interlocked.Increment(ref executionCount);
            _logger.LogInformation("Timed Hosted Service is running. Count:{Count}", count);
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Timed Hosted Service is stopping");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }
    }
}
